const express = require("express");
const userModel = require("./models");
let app = express();

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));

const path = require("path");
const static = express.static;
app.set("views",path.join(__dirname,"./views"))
app.set("view engin","ejs");
app.use(static("./static"));
//初始页面
app.get("/",(req,res)=>{
    res.sendFile(__dirname+"/views/index.html");
})
//添加数据
app.post("/addPostUser", async (req, res) => {
    try {
        await userModel.create(req.body);
        res.json({
            info: "添加成功",
            status: 1
        })

    } catch (err) {
        res.json({
            info: "添加失败",
            status: 0,
            err
        })
    }

})
//更新数据
app.get("/getdata", async (req, res) => {
    let users = await userModel.find();
    res.json(users);
})
// 排序
app.get("/sortdata", async (req, res) => {
    let users = await userModel.find().sort({age:1});
    res.json(users);
})
//性别筛选
app.get("/genderfilter", async (req, res) => {
    let { gender } = req.query;
    let users;
    if (gender === "0") {
        users = await userModel.find();
    }else{
        users = await userModel.find({gender});
    }
    res.json(users);
})
//年龄排序
app.get("/sortage", async (req, res) => {
    let { gender , age } = req.query;
    let users;
    if (age === "0") {
        if (gender === "0") {
            users = await userModel.find().sort();
        }else{
            users = await userModel.find({gender}).sort();
        }
    }else{
        if (gender === "0") {
            users = await userModel.find().sort({age});
        }else{
            users = await userModel.find({gender}).sort({age});
        }
    }
    res.json(users);
})
// 删除用户的接口 
app.get("/deluser", async (req, res) => {
    let { _id } = req.query;
    console.log(_id);
    try {
        await userModel.deleteOne({ _id });
        let userdata = await userModel.find();
        res.json({
            info: "成功",
            status: 1,
            userdata
        })
    } catch (err) {
        res.json({
            info: "删除失败",
            status: 0,
            err
        })
    }

})

app.listen(8989);